package com.compus.entity.vo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> implements Serializable {
  private static final long serialVersionUID = 781837582814609011L;
  private Integer code;
  private String msg;
  private T data;

  private static ObjectMapper objectMapper = new ObjectMapper();

  public Result(Integer code, String msg) {
    this.code = code;
    this.msg = msg;
  }

  public static <T> Result<T> success() {
    return new Result<>(200, "成功");
  }

  public static <T> Result<T> success(Integer code, String msg, T data) {
    return new Result<T>(code, msg, data);
  }

  public static <T> Result<T> success(T data) {
    return new Result<T>(200, "成功", data);
  }

  public static Result fail() {
    return new Result(500, "失败");
  }

  public static Result fail(String msg) {
    return new Result(500, msg);
  }

  public static Result unLogin(String msg) {
    return new Result(401, msg);
  }

  public String toJson() {
    try {
      return objectMapper.writeValueAsString(this);
    } catch (JsonProcessingException e) {
      return Result.fail("json序列化失败").toJson();
    }
  }
}
